<template>
  <div class="movie-list">
    <el-card>
      <template #header>
        <div class="card-header">
          <h2>电影列表</h2>
          <div class="header-actions">
            <el-button
                type="danger"
                :disabled="!store.selectedMovies.length"
                @click="handleBatchDelete"
            >
              批量删除
            </el-button>
<!--            <el-button-->
<!--                type="primary"-->
<!--                :disabled="!store.selectedMovies.length"-->
<!--                @click="handleExport"-->
<!--            >-->
<!--              导出JSON-->
<!--            </el-button>-->
            <el-button
                type="success"
                :disabled="!store.selectedMovies.length"
                @click="exportApiLinks"
            >
              导出API链接
            </el-button>
            <el-button type="primary" @click="goToUpload">
              上传新电影
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索框 -->
      <el-input
          v-model="searchQuery"
          placeholder="搜索电影名称"
          clearable
          class="search-input"
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <!-- 电影列表表格 -->
      <el-table
          v-loading="store.loading"
          :data="store.movies"
          style="width: 100%"
          border
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="电影名字" />
        <el-table-column prop="slug" label="Slug" />
        <el-table-column label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="300" fixed="right">
          <template #default="scope">
            <el-button
                type="primary"
                link
                @click="viewJson(scope.row)"
            >
              查看JSON
            </el-button>
            <el-button
                type="success"
            link
            @click="viewApi(scope.row)"
            >
            查看API
            </el-button>
            <el-button
                type="danger"
                link
                @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination-container">
        <el-pagination
            :current-page="store.pagination.current"
            :page-size="store.pagination.size"
            :total="store.pagination.total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
        />
      </div>

      <!-- 删除确认对话框 -->
      <el-dialog
          v-model="deleteDialogVisible"
          title="确认删除"
          width="30%"
      >
        <p>{{ batchDelete ? '确定要删除选中的电影吗？' : '确定要删除这部电影吗？' }}</p>
        <template #footer>
          <el-button @click="deleteDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="confirmDelete">确定</el-button>
        </template>
      </el-dialog>

      <!-- JSON 查看对话框 -->
      <el-dialog
          v-model="detailDialogVisible"
          title="电影详情"
          width="70%"
          class="movie-detail-dialog"
      >
        <movie-detail-view
            v-if="currentMovie"
            :movie-data="currentMovie"
        />
      </el-dialog>
    </el-card>
  </div>
</template>

<script setup>
import MovieDetailView from '@/views/admin-json/MovieDetailView.vue'
import { ref, computed, onMounted, watch } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { useMoviesStore } from '@/stores/adminMovie'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage,ElMessageBox  } from 'element-plus'

const detailDialogVisible = ref(false)
const currentMovie = ref(null)
const store = useMoviesStore()
const router = useRouter()
const searchQuery = ref('')
const deleteDialogVisible = ref(false)
const batchDelete = ref(false)
const currentDeleteId = ref(null)

// 处理选择变化
const handleSelectionChange = (selection) => {
  store.setSelectedMovies(selection)
}

// 处理单个删除
const handleDelete = (row) => {
  batchDelete.value = false
  currentDeleteId.value = row.id
  deleteDialogVisible.value = true
}

// 处理批量删除
const handleBatchDelete = () => {
  if (!store.selectedMovies.length) {
    ElMessage.warning('请选择要删除的电影')
    return
  }
  batchDelete.value = true
  deleteDialogVisible.value = true
}

// 确认删除
const confirmDelete = async () => {
  try {
    if (batchDelete.value) {
      const ids = store.selectedMovies.map(movie => movie.id)
      await store.batchDeleteMovies(ids)
      ElMessage.success('批量删除成功')
    } else {
      await store.deleteMovie(currentDeleteId.value)
      ElMessage.success('删除成功')
    }
    deleteDialogVisible.value = false
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 处理导出
const handleExport = async () => {
  try {
    const ids = store.selectedMovies.map(movie => movie.id)
    const response = await store.exportMovies(ids)
    if (response && response.data) {
      // 创建下载
      const blob = new Blob(
          [JSON.stringify(response.data, null, 2)],
          { type: 'application/json' }
      )
      const url = window.URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `movies_export_${new Date().getTime()}.json`
      link.click()
      window.URL.revokeObjectURL(url)
      ElMessage.success('导出成功')
    }
  } catch (error) {
    ElMessage.error('导出失败: ' + error.message)
  }
}

// 监听搜索输入
watch(searchQuery, (newValue) => {
  store.setSearchName(newValue)
})

// 处理分页变化
const handleCurrentChange = async (current) => {
  await store.fetchMovies({ current: current })
}

const handleSizeChange = async (size) => {
  await store.fetchMovies({
    current: 1,  // 切换每页大小时重置到第一页
    size: size
  })
}

// 查看JSON
const viewJson = async (movie) => {
  try {
    const response = await store.fetchMovieJson(movie.slug)
    if (response.data.status) {
      currentMovie.value = response.data  // 后端返回的是完整的对象
      detailDialogVisible.value = true
    } else {
      ElMessage.error(response.data.msg || '获取电影详情失败')
    }
  } catch (error) {
    ElMessage.error('获取电影详情失败')
  }
}

// 查看API地址
const viewApi = async (movie) => {
  // 拼接API地址
  const apiUrl = `https://api.jalatv.top/phim/${movie.slug}`

  // 使用对话框显示API地址
  await ElMessageBox.alert(apiUrl, 'API地址', {
    confirmButtonText: '复制',
    callback: (action) => {
      if (action === 'confirm') {
        navigator.clipboard.writeText(apiUrl).then(() => {
          ElMessage.success('API地址已复制到剪贴板')
        }).catch(() => {
          ElMessage.error('复制失败，请手动复制')
        })
      }
    }
  })
}

const exportApiLinks = () => {
  if (!store.selectedMovies.length) {
    ElMessage.warning('请选择要导出的电影')
    return
  }

  // 生成API链接列表
  const apiLinks = store.selectedMovies.map(movie => ({
    name: movie.name,
    api_url: `https://api.jalatv.top/apis/movie/api/movies/${movie.name}`
  }))

  // 创建导出内容
  const exportContent = apiLinks.map(item =>
      `${item.name}\t\t${item.api_url}`
  ).join('\n')

  // 创建Blob对象
  const blob = new Blob([exportContent], { type: 'text/plain' })
  const url = window.URL.createObjectURL(blob)

  // 创建下载链接
  const link = document.createElement('a')
  link.href = url
  link.download = `movie_api_links_${new Date().getTime()}.txt`

  // 触发下载
  document.body.appendChild(link)
  link.click()

  // 清理
  document.body.removeChild(link)
  window.URL.revokeObjectURL(url)

  ElMessage.success(`成功导出 ${apiLinks.length} 个API链接`)
}

const goToUpload = () => {
  router.push('/admin-json/upload')
}

// 格式化日期
const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString()
}

onMounted(() => {
  store.fetchMovies()
})
</script>

<style scoped>
.movie-detail-dialog .el-dialog__body {
  padding: 20px;
}
.header-actions {
  display: flex;
  gap: 10px;
}
.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
.movie-list {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-input {
  margin-bottom: 20px;
  width: 300px;
}

pre {
  white-space: pre-wrap;
  word-wrap: break-word;
}
</style>